package com.zeny.express.framework.config.impl;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import javax.annotation.PostConstruct;

import org.apache.curator.framework.recipes.cache.ChildData;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.framework.recipes.cache.PathChildrenCache.StartMode;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.zeny.express.framework.config.ConfigurationService;
import com.zeny.express.framework.config.CuratorFrameworkFactoryBean;

/**
 * 配置参数服务
 * 
 * @author zhuwei
 * @date 2013年8月30日 下午8:22:55
 */
public class ConfigurationServiceImpl implements ConfigurationService {

	/**
	 * 日志
	 */
	private static final Logger LOGGER = LoggerFactory
			.getLogger(ConfigurationServiceImpl.class);

	/**
	 * Zookeeper Curator 框架
	 */
	@Autowired
	private CuratorFrameworkFactoryBean curatorFrameworkFactoryBean;

	/**
	 * 需要监听组节点
	 */
	private Set<String> groups;

	/**
	 * 组缓存数据
	 */
	private Map<String, PathChildrenCache> cacheMap;

	/**
	 * 初始化
	 * 
	 * @author zhuwei
	 * @date 2013年8月30日 下午8:24:35
	 * @throws Exception
	 */
	@PostConstruct
	public void init() throws Exception {

		LOGGER.info("[framework] start init ConfigurationService: ");

		cacheMap = new HashMap<String, PathChildrenCache>();
		PathChildrenCacheListener listener = new PathChildrenCacheListenerImpl();

		for (String group : groups) {
			LOGGER.info("[framework] configuration path: " + group);
			PathChildrenCache cache = new PathChildrenCache(
					curatorFrameworkFactoryBean.getCuratorFramework(), group, true);
			cache.start(StartMode.BUILD_INITIAL_CACHE);
			cache.getListenable().addListener(listener);
			cacheMap.put(group, cache);
		}

		LOGGER.info("[framework] finish init ConfigurationService: ");

	}

	/**
	 * 获取参数值
	 * 
	 * @author zhuwei
	 * @date 2013年8月30日 下午8:24:12
	 * @see com.zeny.express.framework.config.ConfigurationService#getValue(java.lang.String,
	 *      java.lang.String)
	 */
	@Override
	public String getValue(String group, String key) {
		ChildData data = cacheMap.get(group).getCurrentData(group + "/" + key);
		return new String(data.getData());
	}

	/**
	 * 检查参数是否存在
	 * 
	 * @author zhuwei
	 * @date 2013年8月30日 下午8:24:13
	 * @see com.zeny.express.framework.config.ConfigurationService#exists(java.lang.String,
	 *      java.lang.String)
	 */
	@Override
	public boolean exists(String group, String key) {
		return cacheMap.get(group).getCurrentData(group + "/" + key) != null;
	}

	/**
	 * @param groups
	 */
	public void setGroups(Set<String> groups) {
		this.groups = groups;
	}

}
